package com.train.webadmin.app.util;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.train.webadmin.config.RSAKeyConfig;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import java.util.Hashtable;

@Component
public class QRcodeUtil {

    public static byte[] getQRCodeImage(Long teacherId, Long classId, Long courseId) throws Exception {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);//去除多余的白边
        long nowTime = new Date().getTime();
        long time = nowTime + 10000;
        String s = String.valueOf(time);
        Long expirationTime = Long.valueOf(s.substring(0, s.length() - 3));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("teacherId", teacherId);
        jsonObject.put("classId", classId);
        jsonObject.put("expirationTime", expirationTime);
        jsonObject.put("courseId",courseId);
        BitMatrix bitMatrix = qrCodeWriter.encode(jsonObject.toString(), BarcodeFormat.QR_CODE, 400, 400);
        ByteArrayOutputStream pngOutPutStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutPutStream);
        byte[] bytes = pngOutPutStream.toByteArray();
        return bytes;
    }

    public static String byteToBase64(Long classId, Long courseId, Long teacherId) throws Exception {
        byte[] a = getQRCodeImage(Long.parseLong(teacherId.toString()), classId,courseId);
        BASE64Encoder encoder = new BASE64Encoder();
        String png = encoder.encodeBuffer(a).trim();
        png = png.replaceAll("\n", "").replaceAll("\r", "");
        return "data:image/jpg;base64," + png;
    }

    public static String deciphering(String data) throws Exception {
        // 将RSA私钥字符串转换为PrivateKey对象
        PrivateKey privateKey = RSAUtil.string2PrivateKey(RSAKeyConfig.getPrivateKey());
        // 将Base64编码的字符串转换为字节数组
        byte[] bytes1 = RSAUtil.base642Byte(data);
        // 使用私钥解密字节数组
        byte[] bytes = RSAUtil.privateDecrypt(bytes1, privateKey);
        // 将解密后的字节数组转换为字符串并返回
        return new String(bytes);
    }
}
